<?php
namespace app\index\model;
use app\index\common\Common;
use think\Db;
use think\Exception;
use think\Model;
use think\Session;

class Notice extends Model
{
    public $type=[0=>'通知',1=>'销售公告'];


    public static function getNotice($search_param,$page_param)
    {
        $noticeClass=new self();

        $where['del_flag']=['=',0];

        if(is_numeric($search_param['type'])){
            $where['type']=['=',$search_param['type']];
        }

        if(!empty($search_param['notice_time'])){
            $where['notice_time']=['=',$search_param['notice_time']];
        }

        if(!empty($search_param['search_key']) && !empty($search_param['search_value'])){
            if($search_param['search_key'] === 'id'){
                $id=explode(' ',$search_param['search_value']);
                $where[$search_param['search_key']]=['in',$id];
            }else {
                $where[$search_param['search_key']] = ['like', '%' . $search_param['search_value'] . '%'];
            }
        }

        $obj=$noticeClass->where($where)
            ->field('id,title,content,type,DATE_FORMAT(notice_time,\'%Y-%m-%d\') notice_time')
            ->order('create_time desc')
            ->paginate($page_param['page_size'],false,['page'=>$page_param['page_num']])
            ->each(function($item, $key){
                if(strlen($item->content)>150) {
                    $item->content = mb_substr($item->content, 0, 150) . '.....';
                }
            });

        $data=$obj->items();
        $total=$obj->total();

        return ['status'=>true,'result'=>['data'=>$data,'total'=>$total]];
    }

    public static function getNoticeParam()
    {

    }

    public static function getNoticeTitleList(){
        $noticeClass=new self();

        $where['del_flag']=['=',0];
        $where['notice_time']=['<',date('Y-m-d H:i:s')];
        $data=$noticeClass->where($where)
            ->field('id,title,content,type,notice_time')
            ->order('notice_time desc,create_time desc')
            ->limit(60)
            ->select()->each(function($item, $key){
                if(strlen($item->content)>150) {
                    $item->content = mb_substr($item->content, 0, 150) . '.....';
                }
            })->toArray();

        return ['status'=>true,'result'=>['data'=>$data]];
    }

    public static function addNotice($insert_data,$product){
        $NoticeClass=new self;
        $NoticeProductClass=new NoticeProduct();
        $NoticeProductMarkClass=new NoticeProductMark();

        $NoticeClass->startTrans();
        try {
            $result=$NoticeClass->isUpdate(false)->save($insert_data);
            if($result===false){
                return ['status'=>false,'result'=>'添加公告失败'];
            }
            $notice_id=$NoticeClass->id;
            if(!empty($product)) {
                $insert_product = [];
                foreach ($product as $key => $value) {
                    $insert_product[] = ['notice_id' => $notice_id, 'pro_id' => $value['pro_id'],'remark'=>$value['remark']??''];
                }
                $result = $NoticeProductClass->isUpdate(false)->saveAll($insert_product);
                if ($result === false) {
                    return ['status' => false, 'result' => '添加商品失败'];
                }
                $insert_mark=[];
                foreach ($result as $key=>$value){
                    foreach ($product[$key]['checkedMarks'] as $item) {
                        $insert_mark[] = ['notice_pro_id'=>$value->id,'mark_id'=>$item];
                    }
                }
                $result = $NoticeProductMarkClass->isUpdate(false)->saveAll($insert_mark);
                if ($result === false) {
                    return ['status' => false, 'result' => '添加商品标记失败'];
                }
            }
            $NoticeClass->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch (Exception $e){
            $NoticeClass->rollback();
            trace('addNotice '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'];
        }
    }

    public static function getNoticeById($id){
        $NoticeClass=new self();
        $NoticeProductClass=new NoticeProduct();
        $notice_data=$NoticeClass->where('id',$id)->where('del_flag',0)->field('id,title,content,type,notice_time')->find();
        if(empty($notice_data)){
            return ['status'=>false,'result'=>'未找到数据'];
        }
        if($notice_data['notice_time']<date('Y-m-d ').'00:00:00'){
            return ['status'=>false,'result'=>'已不可编辑'];
        }

        if($notice_data['type']===1){
            $product=$NoticeProductClass->alias('np')
                ->join('product p','np.pro_id=p.id','left')
                ->join('notice_product_mark npm','np.id=npm.notice_pro_id and npm.del_flag=0','left')
                ->where('np.notice_id',$id)
                ->where('np.del_flag',0)
                ->field('np.pro_id,p.en_name,np.remark,group_concat(npm.mark_id) marks')
                ->group('np.pro_id')
                ->select()->toArray();
            $product_list=[];
            $child_key=0;
            foreach ($product as $key=>$value){
                $marks=[];
                if($value['marks']){
                    $marks=explode(',',$value['marks']);
                }
                $product_list[]=['keys'=>$child_key,'en_name'=>$value['en_name'],'pro_id'=>$value['pro_id'],'id'=>$value['pro_id'],'checkedMarks'=>$marks,'remark'=>$value['remark']];
                $child_key++;
            }
            $notice_data['product']=$product_list;
            $notice_data['child_keys']=$child_key;
        }
        return ['status'=>true,'result'=>$notice_data];
    }

    public static function updateNotice($data,$product){
        $NoticeClass=new self;
        $NoticeProductClass=new NoticeProduct();
        $NoticeProductMarkClass=new NoticeProductMark();

        $NoticeClass->startTrans();
        try {
            $result=$NoticeClass->isUpdate(true)->save($data);
            if($result===false){
                return ['status'=>false,'result'=>'添加公告失败'];
            }
            $notice_id=$NoticeClass->id;
            if(!empty($product)) {
                $notice_pro_id=$NoticeProductClass->where('notice_id',$data['id'])->column('id');
                if(!empty($notice_pro_id)){
                    $result=$NoticeProductClass->where('id','in',$notice_pro_id)->delete();
                    if($result===false){
                        return ['status'=>false,'result'=>'删除旧商品失败'];
                    }
                    $NoticeProductMarkClass->where('notice_pro_id','in',$notice_pro_id)->delete();
                    if($result===false){
                        return ['status'=>false,'result'=>'删除旧商品标签失败'];
                    }
                }

                $insert_product = [];
                foreach ($product as $key => $value) {
                    $insert_product[] = ['notice_id' => $notice_id, 'pro_id' => $value['pro_id'],'remark'=>$value['remark']??''];
                }
                $result = $NoticeProductClass->isUpdate(false)->saveAll($insert_product);
                if ($result === false) {
                    return ['status' => false, 'result' => '添加商品失败'];
                }
                $insert_mark=[];
                foreach ($result as $key=>$value){
                    foreach ($product[$key]['checkedMarks'] as $item) {
                        $insert_mark[] = ['notice_pro_id'=>$value->id,'mark_id'=>$item];
                    }
                }
                $result = $NoticeProductMarkClass->isUpdate(false)->saveAll($insert_mark);
                if ($result === false) {
                    return ['status' => false, 'result' => '添加商品标记失败'];
                }
            }
            $NoticeClass->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch (Exception $e){
            $NoticeClass->rollback();
            trace('addNotice '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'];
        }
    }

    public static function getNoticeDetailById($id){
        $NoticeClass=new self();
        $NoticeProductClass=new NoticeProduct();
        $notice_data=$NoticeClass->where('id',$id)->where('del_flag',0)->field('id,title,content,type,notice_time')->find();
        if(empty($notice_data)){
            return ['status'=>false,'result'=>'未找到数据'];
        }
        if($notice_data['type']===1){
            $product=$NoticeProductClass->alias('np')
                ->join('product p','np.pro_id=p.id','left')
                ->join('notice_product_mark npm','np.id=npm.notice_pro_id and npm.del_flag=0','left')
                ->where('np.notice_id',$id)
                ->where('np.del_flag',0)
                ->field('np.pro_id,p.en_name,p.cn_name,p.image,p.introduction,np.remark,p.selling_price,group_concat(npm.mark_id) marks')
                ->group('np.pro_id')
                ->select()->toArray();
            $product_list=[];
            foreach ($product as $key=>$value){
                if($value['marks']){
                    $value['marks']=explode(',',$value['marks']);
                    sort($value['marks'],SORT_NUMERIC);
                }
                $value['image_thumb'] = Common::getThumbImage($value['image']);
                $product_list[]=$value;
            }
            $notice_data['product']=$product_list;
        }
        return ['status'=>true,'result'=>$notice_data];
    }
}